package com.livesource.client.webservices.github;

import java.util.HashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.InitializeLiveSource;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;
import com.livesource.client.model.project.Project;
import com.livesource.client.utilities.ConvertJson;
import com.livesource.client.utilities.EncryptText;
import com.livesource.client.utilities.FileExtensions;
import com.livesource.client.utilities.GetCookies;

public class RequestGithubListFiles {

	public static void getJsonpRequest(final Project project) {

		String authenticationToken = EncryptText.decrypt(GetCookies
				.getGithubAuthenticationToken());

		final GithubAPIServiceAsync githubAPIService = GWT
				.create(GithubAPIService.class);

		if (!(authenticationToken == null || "".equals(authenticationToken))) {

			githubAPIService.githubListFiles(authenticationToken,
					project.getRepositoryURL(), new AsyncCallback<String>() {

						public void onFailure(final Throwable caught) {
							System.out.println(caught);
						}

						public void onSuccess(final String jsonResult) {

							if (jsonResult != null) {

								JSONObject obj = (JSONObject) JSONParser
										.parseStrict(jsonResult);

								JSONArray objArray = ConvertJson
										.convertToArray(obj.get("tree"));

								HashMap<String, ProjectClass> files = new HashMap<String, ProjectClass>();

								for (int i = 0; i < objArray.size(); i++) {

									JSONObject entry = (JSONObject) objArray
											.get(i);

									ProjectClass projectEntry = ConvertGithubToProjectEntry
											.convertJsonp(entry);

									files.put(projectEntry.toString(),
											projectEntry);

									if (FileExtensions.isTextFile(projectEntry
											.getFileExtension())) {

										RequestGithubFileContent
												.getJsonpRequest(project,
														projectEntry);
									}
								}

								LiveSourceGlobalVariables.projectEntries = files;

								InitializeLiveSource.loadPanel();
							}
						}
					});
		}
	}
}
